package com.tuo51.components.redis;

import com.google.common.collect.ImmutableMap;
import com.matt.commons.exception.BusinessException;
import com.tuo51.foudation.utils.JsonUtil;
import com.tuo51.foudation.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

import static com.tuo51.foudation.constant.RedisConstant.*;
import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static com.matt.commons.model.ErrorCode.TICKET_EXPIRED;

/**
 * *******************************
 * Created by Ron.
 * form com.tuo51
 * on 2017/8/4
 * *******************************
 */
@Slf4j
public class RedisCache {

    private static final String TICKET_FORMAT = "%s-%s-%s";

    private static final String TICKET_EXPIRED_MSG="ticket 已过期，请重新登录!" ;

    @Autowired
    private RedisService redisService;


    public String produceSmsCode(String phone, String code) {
        redisService.saveValue(phone, CODE_EXPIRED_TIME, code);
        return code;
    }

    public String getSmsCode(String phone) {
        String value = redisService.getValue(phone);
        return value;
    }

    public String produceTicket(String staffId, Integer channel) {
        String key = SignUtil.mySign(staffId + channel, "utf-8");
        redisService.deleteLike(key + "-" + channel);
        String ticket = String.format(TICKET_FORMAT, key, channel, System.currentTimeMillis());
        Long expiredTime = 0L;

        expiredTime = PHONE_TICKET_EXPIRED_TIME;

        redisService.saveValue(ticket, expiredTime, JsonUtil.toJson(ImmutableMap.of(STAFF_KEY, staffId)));
        return ticket;
    }

    public Map getCacheMap(String ticket) {
        String value = redisService.getValue(ticket);
        if (StringUtils.isBlank(value))
            return null;
        Map response = JsonUtil.readToMap(value);
        response.put(TICKET, ticket);
        return response;
    }

    public boolean refreshTime(String ticket){
        redisService.refreshTime(ticket, PAD_TICKET_EXPIRED_TIME);
        return true;
    }


    public String getStaffId(String ticket) {
        String value = redisService.getValue(ticket);
        if (StringUtils.isBlank(value))
            throw new BusinessException(TICKET_EXPIRED, TICKET_EXPIRED_MSG);
        Map cache = JsonUtil.readToMap(value);
        if (cache.get(STAFF_KEY) == null)
            throw new BusinessException(TICKET_EXPIRED, TICKET_EXPIRED_MSG);

        return cache.get(STAFF_KEY).toString();
    }
}
